<?php
/**
 * Created by PhpStorm.
 * User: yuanjie
 * Date: 15/12/3
 * Time: 下午3:19
 */
class SceShopController extends BaseController {
    /*
     * 车辆确认停车入工位
     * */
    /**
     * @Author:      lyt
     * @DateTime:    2016-02-14 14:30:44
     * @Description: 添加 该接口的 参数
     * 添加 该接口使用的参数  添加参数 车型id
     * @link： http://www.activity.com/v1/sce/shop/car_login_work_station?token=284f8d86c9fb637c17b705e39b9774ab&car_no=%E4%BA%ACA66666&shop=1&station=1&car_model_id=985
     */
    public function car_login_work_station(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'car_no' => 'required',
                'shop' => 'required',
                'station' => 'required',
                'car_model_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $car_no = strtoupper(Input::get('car_no'));
            $shop = Input::get('shop');
            $station = Input::get('station');
            $car_model_id = Input::get('car_model_id');
            $mileage = Input::get('mileage') ? Input::get('mileage') : 0;
            $vin_code = strtoupper(Input::get('vin'));
            $insurance = Input::get('insurance');

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                break;
            }
            if($shop!=$engineer_data->type_id){
                $response = Lang::get("sce_error.order_note_shop_error_1013");
                break;
            }
            $mscs=MaintenanceStationCarStatus::where("shop_id",$engineer_data->type_id)->whereIn("status",array(1,2))->where("station_id",$station)->first();
            if($mscs){
                if($mscs->car_no == Input::get('car_no')){
                    $response = Lang::get("sce_error.work_station_car_no_empty1014");
                    break;
                }else{
                    $response = Lang::get("sce_error.work_station_exiet_1018");
                    break;
                }
            }

            try{
                MaintenanceStationCarStatus::where('shop_id',$shop)
                    ->where('station_id',$station)
                    ->update(array('status' => 1 , 'car_no' => $car_no,"car_model_id"=>$car_model_id,'mileage'=>$mileage,'vin_code'=>$vin_code,'insurance'=>$insurance));

                //记录车辆进入工位时间（开始时间）
                $station_start_time = MaintenanceStationDetails::InsertDetails($station,$shop);
//                if(is_null($station_start_time)){
//                    $response = Lang::get("sce_error.station_car_start_time_exiet_1001");
//                    break;
//                }
//                if($station_start_time == '0'){
//                    $response = Lang::get("sce_error.station_car_start_time_exiet_1002");
//                    break;
//                }
//                if($station_start_time == '1'){
//                    $response = Lang::get("sce_error.station_car_start_time_exiet_1003");
//                    break;
//                }
//                if($station_start_time == '3'){
//                    $response = Lang::get("sce_error.work_station_car_no_empty1014");
//                    break;
//                }
//                if($station_start_time == '4'){
//                    $response = Lang::get("sce_error.station_car_start_time_exiet_1004");
//                    break;
//                }

            } catch (Exception $e) {
                Log::error("error", array("system" => "sce" ,"event" => "car_login_work_station", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("sce_error.order_update_error_1009");
                break;
            }
            $result = array(
                'car_no' => $car_no,
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "car_login_work_station", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:    2016-02-14 14:32:07
     * @Description: 用户将 正在进行中得订单 回到 工位上
     * @link：http://www.activity.com/v1/sce/shop/order_login_work_station?token=d0a82d8388dd86a2c2a8a34c59e94160&order_id=14647139334477&shop=1&station=3
     *
     */
    public function order_login_work_station(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',               
                'station' => 'required', 
                'order_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id');
            $station = Input::get('station');

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                $response = Lang::get("sce_error.user_token_not_exist_1004");
                break;
            }

            $order=Orders::find($order_id);
            $mp=MaintenancePark::where("shop_id",$engineer_data->type_id)->where("order_id",$order_id)->where("status",4)->first();
            if(is_null($mp)){
                $response = Lang::get("sce_error.order_notexiet_1015");
                break;
            }
            if(is_null($order)){
                $response = Lang::get("sce_error.order_notexiet_1015");
                break;
            }
            if($order->shop_id!=$engineer_data->type_id){
                $response = Lang::get("sce_error.order_note_shop_error_1016");
                break;
            }
            if($order->engineer_id!=$engineer_data->id){
                $response = Lang::get("sce_error.order_engineer_error_1017");
                break;
            }
            if(!in_array($order->status,array(1213,1214,1215,1216))){//订单状态是正确
                $response = Lang::get("sce_error.order_status_error_1010");
                break;
            }
            $mscs=MaintenanceStationCarStatus::where("shop_id",$engineer_data->type_id)->whereIn("status",array(1,2))->where("station_id",$station)->first();
            if($mscs){
                if($mscs->car_no == Input::get('car_no')){
                    $response = Lang::get("sce_error.work_station_car_no_empty1014");
                    break;
                }else{
                    $response = Lang::get("sce_error.work_station_exiet_1018");
                    break;
                }
            }
            $mp=MaintenancePark::where("shop_id",$engineer_data->type_id)->where("order_id",$order_id)->where("status",4)->delete();
            MaintenanceStationCarStatus::where("station_id",$station)->update(array("car_no"=>$order->car_no,"status"=>2,"car_model_id"=>$order->car_model_id,"order_id"=>$order->order_id));
            // $order_service_engineers = new OrderServiceEngineers();
            // $order_service_engineers->order_id = $order_id;
            // $order_service_engineers->product_id = $product_id;
            // $order_service_engineers->engineer_id = $select_engineer_id;
            // $order_service_engineers->engineer_type  = 'assist';
            // $order_service_engineers->auditor_id = $auditor->id;
            // $order_service_engineers->created_at = Common::num2DateTime(time());
            // $order_service_engineers->updated_at = Common::num2DateTime(time());
            // $order_service_engineers->save();

            //记录车辆进入工位时间（开始时间）
            $station_start_time = MaintenanceStationDetails::InsertDetails($station,$engineer_data->type_id);
//            if(is_null($station_start_time)){
//                $response = Lang::get("sce_error.station_car_start_time_exiet_1001");
//                break;
//            }
//            if($station_start_time == '0'){
//                $response = Lang::get("sce_error.station_car_start_time_exiet_1002");
//                break;
//            }
//            if($station_start_time == '1'){
//                $response = Lang::get("sce_error.station_car_start_time_exiet_1003");
//                break;
//            }
//            if($station_start_time == '3'){
//                $response = Lang::get("sce_error.work_station_car_no_empty1014");
//                break;
//            }
//            if($station_start_time == '4'){
//                $response = Lang::get("sce_error.station_car_start_time_exiet_1004");
//                break;
//            }

            $result = array(
                'order_id' => $order_id,
            );
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' =>$result);
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "car_login_work_station", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author   lyt                      <ahlyt@anhuibj.com>
     * @DateTime 2018-03-14T11:06:47+0800
     * @return   [type]                   [description]
     * 培训信息列表
     */
    public function traininglists(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "page"=>'integer',
                "page_size"=>'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $token = Input::get("token");
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                $response = Lang::get("sce_error.user_token_not_exist_1004");
                break;
            }
            $page_size=Input::get("page_size",20);
            $page=Input::get("page",1);
            $title = Input::get("title");
            $lable = Input::get("lable");
            
            $res = TrainMessage::LeftJoin('system_users as su1', 'su1.id', '=', 'train_message.updated_by')
                    ->where('train_message.status',1);
            if($lable){
                $lable=json_decode(Input::get('lable'),true);
                $ids=TrainMessageLabel::whereIn("label_id",$lable)->select("message_id")->get();
                $temp_id=array();
                foreach ($ids as $_ids) {
                    $temp_id[]=$_ids->message_id;
                }
                $res->whereIn('train_message.id',$temp_id);
            }
            if($title){
                $res->where('train_message.title', 'like', '%'.$title.'%');
            }

            $count = $res->count();
            $res = $res->skip($page_size * ($page - 1))
                    ->take($page_size)
                    ->select('train_message.id', 'train_message.title', 'train_message.updated_at', 'su1.name as sys_name')
                    ->orderBy('train_message.view_times', 'desc')
                    ->orderBy('train_message.id', 'asc')
                    ->get();
            foreach ($res as $_h) {
                $bd=DB::select("SELECT
                        GROUP_CONCAT(li.`name` SEPARATOR '/') as lab_name
                    FROM
                        `train_message` hs
                    LEFT JOIN  train_message_label hml ON hs.id=hml.message_id
                    LEFT JOIN  labels_info li ON li.id = hml.label_id
                    where hs.id=?", array($_h->id)); 
                $_h->lab_name=$bd[0]->lab_name;
            }
            //标签列表
            $lable = LabelsInfo::where('type', '3')
                    ->where('status', '1')
                    ->select('id','name')
                    ->orderBy('id','asc')
                    ->get();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array('count' => $count, 'public_data' => $res, 'lable' => $lable));
        }while(false);
        return json_encode($response);
    }
    
   /**
    * @Author   lyt                      <ahlyt@anhuibj.com>
    * @DateTime 2018-03-14T11:10:15+0800
    * @return   [type]                   [description]
    */
    public function trainingdesc() {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $token = Input::get("token");
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                $response = Lang::get("sce_error.user_token_not_exist_1004");
                break;
            }
            $pm = TrainMessage::LeftJoin('system_users as su1', 'su1.id', '=', 'train_message.updated_by')
                    ->where("train_message.id",Input::get("id"))
                    ->select('train_message.id','train_message.title','train_message.updated_at','train_message.status', 'su1.name as sys_name','train_message.content')
                    ->first();
            if(is_null($pm)){
                $response = Lang::get("scs_error.public_error_31016");
                break;
            }
            $lab_array = TrainMessageLabel::LeftJoin("labels_info","labels_info.id","=","train_message_label.label_id")
                    ->where("train_message_label.message_id",Input::get("id"))
                    ->select("labels_info.id","labels_info.name")
                    ->get();
            DB::update("update train_message set view_times=view_times+1 where id =?",array(Input::get("id")));
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array('training_info' => $pm, 'lable_info' => $lab_array));
        }while(false);
        return json_encode($response);
    }
    
    /**
     * @Author:          zk
     * @DateTime:        18-5-21 下午4:00
     * @Description:     车辆入停车场
     * @param string $token             用户token
     * @param string $order_id          订单编号
     * @param int $shop_id              门店id
     * @link http://api.anhui.com/v1/sce/shop/inPark?token=0ca286600fa68167783433b82d4422cb&order_id=15226558329029&shop_id=1
     * http://www.activity.com/v1/sce/shop/inPark?token=284f8d86c9fb637c17b705e39b9774ab&order_id=14647139334477&shop_id=1   （现用）
     */
    public function inPark(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'shop_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $token = Input::get("token");
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                $response = Lang::get("sce_error.user_token_not_exist_1004");
                break;
            }
            $order_id = Input::get('order_id');
            $shop_id = Input::get('shop_id');   //$engineer_data->type_id  也可以作为门店id
            
            $orders = Orders::find($order_id);
            if(is_null($orders)){
                $response = Lang::get("sce_error.order_notexiet_1015");
                break;
            }
            if($orders->shop_id != $shop_id){
                $response = Lang::get("sce_error.order_note_shop_error_1016");
                break;
            }
            if(!in_array($orders->status, Orders::$in_park)){//判断是否符合可停入停车场状态
                $response = Lang::get("sce_error.order_status_error_1010");
                break;
            }

            //工位占用详细信息入库(结束时间)
            try {
                $station_start_time = MaintenanceStationDetails::UpdatedDetails($order_id,$shop_id);
            }catch(Exception $e){
                Log::error("error", array("system" => "scs" ,"event" => "UpdatedDetails", 'input' =>Input::all() ,"exception" => $e));
            }
//            if(is_null($station_start_time)){
//                $response = Lang::get("sce_error.station_car_start_time_exiet_1001");
//                break;
//            }
//            if($station_start_time == '0'){
//                $response = Lang::get("sce_error.station_car_start_time_exiet_1002");
//                break;
//            }
//            if($station_start_time == '1'){
//                $response = Lang::get("sce_error.station_car_start_time_exiet_1003");
//                break;
//            }
//            if($station_start_time == '4'){
//                $response = Lang::get("sce_error.station_car_start_time_exiet_1004");
//                break;
//            }

            $mc = MaintenancePark::where('order_id', $order_id)->get();
            if(count($mc)>0){//判断是否符合可停入停车场状态
                $mscs = MaintenanceStationCarStatus::where('order_id', $order_id)
                        ->update(array("car_no"=>"","status"=>0,"car_model_id"=>0,"order_id"=>0,'mileage'=>0,'vin_code'=>'','insurance'=>'','start_off_time'=>''));
                $response = Lang::get("sce_error.park_status_error_1026");
                break;
            }

            //入停车场记录
            $mp = new MaintenancePark();
            $mp->shop_id = $shop_id;
            $mp->order_id = $order_id;
            if(in_array($orders->status, array(1215))){
                $status=4;
            }else if($orders->book_type==1){
                $status=2;
            }else{
                $status=3;
            }
            $mp->status=$status;
            $mp->operation_type = 2;    //操作平台 1:门店;2:技师端;
            $mp->user_id = $engineer_data->id;
            $mp->save();



            //腾出车位
            $mscs=MaintenanceStationCarStatus::where('order_id', $order_id)
                    ->update(array("car_no"=>"","status"=>0,"car_model_id"=>0,"order_id"=>0,'mileage'=>0,'vin_code'=>'','insurance'=>'','start_off_time'=>''));
            $response = array('code' => 0, 'msg' => 'ok', 'result' => ['order_id' => $order_id]);


        }while(false);
        
        Log::info("info", array("system" => "sce" ,"event" => "inPark", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
}